package com.bird.system.domain.bo;

import org.springframework.util.StringUtils;


public final class Address {

	private static final String PREFIX_AMQP = "proxy://";

	private static final int DEFAULT_PORT = 80;

	private String host;

	private int port;

	private String username;

	private String password;

	private String authorization;

	public Address(String input) {
		input = input.trim();
		input = trimPrefix(input);
		input = parseUsernameAndPassword(input);
		input = parseVirtualHost(input);
		parseHostAndPort(input);
	}

	private String trimPrefix(String input) {
		if (input.startsWith(PREFIX_AMQP)) {
			input = input.substring(PREFIX_AMQP.length());
		}
		return input;
	}

	private String parseUsernameAndPassword(String input) {
		if (input.contains("@")) {
			String[] split = StringUtils.split(input, "@");
			String creds = split[0];
			input = split[1];
			split = StringUtils.split(creds, ":");
			this.username = split[0];
			if (split.length > 0) {
				this.password = split[1];
			}
		}
		return input;
	}

	private String parseVirtualHost(String input) {
		int hostIndex = input.indexOf('/');
		if (hostIndex >= 0) {
			this.authorization = input.substring(hostIndex + 1);
			if (this.authorization.isEmpty()) {
				this.authorization = "/";
			}
			input = input.substring(0, hostIndex);
		}
		return input;
	}

	private void parseHostAndPort(String input) {
		int portIndex = input.indexOf(':');
		if (portIndex == -1) {
			this.host = input;
			this.port = DEFAULT_PORT;
		} else {
			this.host = input.substring(0, portIndex);
			this.port = Integer.valueOf(input.substring(portIndex + 1));
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAuthorization() {
		return authorization;
	}

	public void setAuthorization(String authorization) {
		this.authorization = authorization;
	}

	@Override
	public String toString() {
		return host + ":" + port;
	}
}
